<template>
  <div class="tableListBox">
    <el-scrollbar style="height: 100%">
      <div class="common-header">
        <div style="cursor: pointer" @click="back">
          <i class="vxe-icon-arrow-left" style="vertical-align: middle"></i><span style="vertical-align: middle">返回</span>
        </div>
        <div>
          <el-button v-if="form.contractInfo.contractStatus !== 'COMPLETED'" type="primary" size="small"
            @click="edit">编辑</el-button>
          <el-button type="primary" size="small" @click="discard">作废</el-button>
        </div>
      </div>
      <div class="anthorContent" style="padding: 20px; margin: 50px 0 0">
        <el-tabs v-model="active">
          <el-tab-pane label="收样信息" name="first">
            <p class="title"><span class="titleName">基础信息</span></p>


            <el-form label-width="106px" label-position="top" :inline="false" :model="form" size="normal" ref="form">

              <div class="task_content">
                <div style="width: 100%">
                  <el-row :gutter="30">
                    <el-col :span="6">
                      <el-form-item label="工程名称" prop="projectName">
                        <el-input class="el-input" size="mini" disabled
                          v-model="form.contractInfo.projectName"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="报告编号">
                        <el-input size="mini" v-model="form.reportNumber" disabled></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="委托编号">
                        <el-input size="mini" v-model="form.entrustNumber" disabled></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="委托日期">
                        <el-input size="mini" :value="formatDate(form.entrustDate)" disabled></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="收样人员">
                        <el-input size="mini" v-model="userInfo.userName" disabled></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="收样时间">
                        <el-input size="mini" :value="formatDate(form.createTime)" disabled></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="是否办理结算">
                        <el-input size="mini" :value="form.settleTime ? '是' : '否'" disabled></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="是否结算完成">
                        <el-input size="mini" :value="form.isSettleCompleted ? '是' : '否'" disabled></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="规格型号">
                        <el-input size="mini" v-model="form.specModel" disabled></el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="生产厂家">
                        <el-input size="mini" v-model="form.manufacturer" disabled></el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="工程部位">
                        <el-input size="mini" v-model="form.engineeringPart" disabled></el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="批号">
                        <el-input size="mini" v-model="form.batchNumber" disabled></el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="委托人">
                        <el-input size="mini" v-model="form.entrustName" disabled></el-input>
                      </el-form-item>
                    </el-col>

                  </el-row>
                </div>
              </div>


            </el-form>

            <!-- <el-descriptions title="" :column="4" class="el-descriptions">
              <el-descriptions-item label="工程名称"><el-tag style="width: 170px;" size="small">{{form.contractInfo.projectName }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="报告编号"><el-tag style="width: 170px;" size="small">{{ form.reportNumber }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="委托编号"><el-tag style="width: 170px;" size="small">{{ form.entrustNumber }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="委托日期"><el-tag style="width: 170px;" size="small">{{ form.entrustDate | parseTime('{y}-{m}-{d}') }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="收样人员"><el-tag style="width: 170px;" size="small">{{ userInfo.userName }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="收样时间"><el-tag style="width: 170px;" size="small">{{ form.createTime | parseTime('{y}-{m}-{d}') }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="是否办理结算"><el-tag style="width: 170px;" size="small">{{ form.settleTime | isBoolean }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="是否结算完成"><el-tag style="width: 170px;" size="small">{{ form.isSettleCompleted | isBoolean }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="规格型号"><el-tag style="width: 170px;" size="small">{{ form.specModel }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="生产厂家"><el-tag style="width: 170px;" size="small">{{ form.manufacturer }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="工程部位"><el-tag style="width: 170px;" size="small">{{ form.engineeringPart }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="批号"><el-tag style="width: 170px;" size="small">{{ form.batchNumber }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="委托人"><el-tag style="width: 170px;" size="small">{{ form.entrustName }}</el-tag></el-descriptions-item>
            </el-descriptions> -->
            <Table ref="settleRecord" :columns="tableColumn" :tableData="form.sampleOrderDetailList"
              :span-method="mergeRowMethod" />
            <p style="text-align: right; margin: 10px 0">
              总价
              <vxe-input :value="form.sampleOrderDetailList | getTotal(isContractPrice ? 'contractPrice' : 'unitPrice')"
                disabled></vxe-input>
            </p>
            <p class="title"><span class="titleName">检测信息</span></p>
            <el-descriptions title="" :column="4">
              <el-descriptions-item label="检测时间">{{ form.timesheetModifyTime | parseTime('{y}-{m}-{d}')
              }}</el-descriptions-item>
              <el-descriptions-item label="检测人">{{ form.timesheetNames }}</el-descriptions-item>
              <el-descriptions-item label="出报告时间">{{ form.submitReportTime |
                parseTime('{y}-{m}-{d}') }}</el-descriptions-item>
              <el-descriptions-item label="出报告人">{{ form.submitReportUserName }}</el-descriptions-item>
              <el-descriptions-item label="提交时间">{{ form.submitReportUserId }}</el-descriptions-item>
              <el-descriptions-item label="提交人">{{ form.submitReportUserId }}</el-descriptions-item>
              <el-descriptions-item label="结算登记时间">{{ form.settleTime | parseTime('{y}-{m}-{d}') }}</el-descriptions-item>
              <el-descriptions-item label="结算人">{{ form.settleUserName }}</el-descriptions-item>
            </el-descriptions>
            <div style="height: 20px"></div>

          </el-tab-pane>


          <el-tab-pane label="附件档案" name="second">
            <p class="title"><span class="titleName">合同附件</span></p>
            <div v-if="form.contractInfo && form.contractInfo.contractFileList && form.contractInfo.contractFileList.length > 0
              " class="anthorContent-item-fileList">
              <div v-for="file in form.contractInfo.contractFileList" :key="file.uid" class="fileList-item">
                <i class="el-icon-paperclip fileList-item-beforeIcon"></i>
                <span class="fileList-item-filename">{{ file.fileName || file.name }}</span>
                <i class="el-icon-download pointer fileList-item-afterIcon" @click="download(file)"></i>
              </div>
            </div>
            <p class="title"><span class="titleName">检测报告</span></p>
            <div v-if="form.reportSubmitFileList && form.reportSubmitFileList.length > 0"
              class="anthorContent-item-fileList">
              <div v-for="file in form.reportSubmitFileList" :key="file.id" class="fileList-item">
                <i class="el-icon-paperclip fileList-item-beforeIcon"></i><span class="fileList-item-filename">{{
                  file.fileName || file.name }}</span>
                <i class="el-icon-download pointer fileList-item-afterIcon" @click="download(file)"></i>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <SelectFromTreeTableDialog ref="treeTable" v-bind="options" v-model="checkParams" @refreshStd="refreshStd"
        @submit="selParam" />
    </el-scrollbar>
  </div>
</template>

<script>
import Table from '/@/components/PartForDialog/table.vue';
import SelectFromTreeTableDialog from '/@/components/SelectFromTreeTableDialog';
import VXETable from 'vxe-table';
import util from '/@/util/util';
export default {
  components: { Table, SelectFromTreeTableDialog },
  data() {
    return {
      userInfo: '',
      active: 'first',
      tableColumn: [
        {
          type: 'seq',
          width: 60,
          title: '序号',
        },
        {
          field: 'itemName',
          title: '检测项目',
          editRender: {},
        },
        {
          field: 'paramName',
          title: '检测参数',
          editRender: {},
        },
        {
          field: 'salesUnit',
          title: '计价单位',
          editRender: {},
        },
        {
          field: 'price',
          title: '单价(元)',
          editRender: {},
          formatter: ({ row }) => {
            return this.isContractPrice ? row.contractPrice : row.unitPrice;
          },
        },
        {
          field: 'detectionStdName',
          title: '检测标准',
          editRender: {},
        },
        {
          field: 'remarks',
          title: '备注',
          editRender: {},
        },
      ],
      tableData: [],
      checkParams: [],
      options: {
        title: '新增检测项目',
        type: 'radio',
        columns: [
          {
            field: 'name',
            type: 'checkbox',
            treeNode: true,
            title: '检测项目 / 检测参数',
            editRender: {},
            slots: {
              default: 'd_itemName',
              // edit: 'e_itemName',
            },
          },
          {
            field: 'itemShortName',
            title: '项目编号拼音简称',
            editRender: {},
          },

          {
            field: 'salesUnit',
            title: '计价单位',
            width: 80,
            align: 'center',
            editRender: {},
          },
          {
            field: 'price',
            title: '单价(元)',
            align: 'center',
            width: 100,
            editRender: {},
            formatter: ({ row }) => {
              return this.isContractPrice ? row.contractPrice : row.unitPrice;
            },
          },
          {
            field: 'domainNames',
            title: '检测领域',
            editRender: {},
          },
          {
            field: 'detectionStdList',
            title: '检测标准',
            editRender: {},
            slots: {
              default: 'd_detectionStdList',
              // edit: 'e_itemName',
            },
          },
          {
            field: 'workingHours',
            title: '工时',
            align: 'center',
            width: 80,
            editRender: {},
          },
          {
            field: 'remarks',
            title: '备注',
            editRender: {},
          },
        ],
        tableData: [],
        total: 0,
      },
      form: {
        contractInfo: {
          projectName: '',
          contractStatus: '',
          contractFileList: [],
        },
        sampleOrderDetailList: [],
        contractFileList: [],
        reportSubmitFileList: [],
        createTime: '',
        reportNumber: '',
        settleTime: '',
        isSettleCompleted: false,
        settleUserId: null,
        settleUserName: null,
        entrustNumber: '',
        pricingType: '',
        entrustDate: '',
        submitReportTime: '',
        submitReportUserName: '',
        timesheetModifyTime: '',
        timesheetNames: '',
      },
    };
  },
  computed: {
    isContractPrice() {
      return this.form.pricingType === 'CONTRACT_PRICE';
    },
  },
  filters: {
    isBoolean(val) {
      return val ? '是' : '否';
    },
    getTotal(list) {
      if (!list || list.length === 0) {
        return 0;
      }
      return list?.reduce((prev, cur) => {
        return (prev += cur.contractPrice);
      }, 0);
    },
  },
  mounted() {
    this.getSampleOrder();
    this.getUserInfo()
  },
  methods: {
    getUserInfo() {
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      this.userInfo = userInfo
    },
    back() {
      this.$router.go(-1);
    },
    //标准时间
    formatDate(dateString) {
      const dateObj = new Date(dateString);

      const year = dateObj.getFullYear();
      const month = String(dateObj.getMonth() + 1).padStart(2, "0");
      const day = String(dateObj.getDate()).padStart(2, "0");

      const formattedDate = `${year}-${month}-${day}`;
      return formattedDate;
    },
    edit() {
      this.$router.push({ path: '/ledgerManage/edit', query: { sampleId: this.$route.query.sampleId } });
    },
    async discard() {
      const type = await VXETable.modal.confirm(`是否确定作废？`);
      if (type === 'confirm') {
        this.discardSampleOrder();
      }
    },
    discardSampleOrder() {
      this.$api.discardSampleOrder({ sampleId: this.$route.query.sampleId }).then((res) => {
        VXETable.modal.message({
          content: '已作废',
          status: 'success',
        });
        this.back();
      });
    },
    // 通用行合并函数（将相同多列数据合并为一行）
    mergeRowMethod({ row, _rowIndex, column, visibleData }) {
      const fields = ['itemName'];
      const cellValue = row[column.property];
      if (cellValue && fields.includes(column.property)) {
        const prevRow = visibleData[_rowIndex - 1];
        let nextRow = visibleData[_rowIndex + 1];
        if (prevRow && prevRow[column.property] === cellValue) {
          return { rowspan: 0, colspan: 0 };
        } else {
          let countRowspan = 1;
          while (nextRow && nextRow[column.property] === cellValue) {
            nextRow = visibleData[++countRowspan + _rowIndex];
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
      }
    },
    getChargeStdList(params = { infoId: null }) {
      this.$api
        .getChargeStdDetail({
          infoId: params.infoId,
        })
        .then((res) => {
          const { chargeStdItemList } = res.data;
          this.options.tableData = chargeStdItemList;
        });
    },
    getSampleOrder() {
      this.$api.getSampleOrder({ sampleId: this.$route.query.sampleId }).then((res) => {
        Object.keys(this.form).forEach((key) => {
          this.form[key] = res.data[key];
          // console.log(this.form.sampleOrderDetailList);
        });
      });
    },
    openDialog() {
      this.getChargeStdList();
      this.$refs.treeTable.dialogVisible = true;
    },
    refreshStd(data) {
      const infoId = data.infoId;
      this.getChargeStdList({ infoId });
    },
    selParam(result) {
      this.checkParams = result;
      this.tableData = result[0].chargeParamList;
    },
    save() { },
    download(file) {
      util.download(file.fileName, file.fileUrl);
    },
    remove() { },
  },
};
</script>






<style lang="scss" scoped>
.anthorContent-item-fileList {
  margin-top: 10px;

  .fileList-item {
    display: inline-block;
    height: 42px;
    line-height: 42px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #cccccc;
    padding: 0 10px;
    margin-bottom: 5px;
    margin-right: 5px;

    .fileList-item-filename {
      height: 22px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.65);
      line-height: 22px;
      text-overflow: ellipsis;
    }

    .fileList-item-beforeIcon {
      color: #1f8fff;
      margin-right: 10px;
    }

    .fileList-item-afterIcon {
      margin-left: 10px;
    }

  }





}


/* 添加底色 */

.el-descriptions span {
  background-color: rgb(231, 231, 251);

}

::v-deep .el-input.is-disabled .el-input__inner {
  background-color: #f0f0f0;
  color: #a3a4a3;
}

::v-deep .el-form-item__label {
  color: #0b2e65;
  font-weight: 500;
  line-height: 0 !important;
  padding: 0 !important;
}

::v-deep .el-form-item__label::before {
  content: " " !important;
}

.el-input {
  font-size: 13px;
}
</style>
